package npu.dce.andcontact1;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import org.json.JSONObject;
import android.database.Cursor;

class Server implements Runnable{
    
	private String SERVERIP = "10.0.2.15";
	private int SERVERPORT = 5554;
  
	private String CLIENTIP = "10.0.2.2";
	private int CLIENTPORT = 5554;
    
	private int CLIENTPORT_ACK = 0;
	
	private UpdatePacket update = new UpdatePacket();
	private boolean update_contact;
    
	private String strVersion, strTypes, strOwner, strGivenName, strMiddleName, strFamilyName, strGender, strSpinPhone, 
	       strPhone, strSpinEmail, strEmail, strSpinIM, strIM, strSpinAddr, strStreet, strPOBox, strCity, strState, strZipCode,
           strCountry, strSpinSNS, strSNS, strSpinOrg1, strOrg1, strSpinOrg2, strOrg2, strNotes, strTime; 
    
	private String Version, Types, Owner, GivenName, MiddleName, FamilyName, Gender, SpinPhone, 
    	   Phone, SpinEmail, Email, SpinIM, IM, SpinPostalAddr, Street, POBox, City, State, ZipCode,
    	   Country, SpinSNS, SNS, SpinOrg1, Org1, SpinOrg2, Org2, Notes, Time;

	private long packetTime, dbTime, contact_id;
	private int count = 0;
	private int numRow;
	
	private byte[] buf, photo, packet_photo, receive_data;
    
	private String photoSize;
    
	private InetAddress inetadd, iadd;
	private DatagramSocket socket;
	private DatagramPacket receive_packet, send_packet;
	private ContactDBAdapter mDbHelper_server;
	private UpdatePacket total_contact;
	private Cursor cur;

    public Server(UpdatePacket total, ContactDBAdapter mDbHelper) {
            total_contact = total;
            mDbHelper_server = mDbHelper;
    }
 
    @Override
    public void run() {
    	// TODO Auto-generated method stub        
        	try {
        	
        		inetadd= InetAddress.getByName(SERVERIP);
        		socket= new DatagramSocket(SERVERPORT,inetadd);
        		
        		while(true){                	
        			try{
        				        				    				
        				buf = new byte[1920];
        				receive_packet = new DatagramPacket(buf,buf.length);
        				
        				socket.receive(receive_packet);        				
        				receive_data = receive_packet.getData();        				
        				update = new UpdatePacket(receive_data, 1920);
	        				
        				strVersion = update.getVersion();        				
        				strTypes = update.getTypes();  
        				strOwner = update.getOwner();
        				strGivenName = update.getGivenName();        				        				         				
        				strMiddleName = update.getMiddleName();
        				strFamilyName = update.getFamilyName();
        				strGender = update.getGender();
        				strSpinPhone = update.getSpinPhone();
        				strPhone = update.getPhone();
        				strSpinEmail = update.getSpinEmail();
        				strEmail = update.getEmail();
        				strSpinIM = update.getSpinIM();
        				strIM = update.getIM();
        				strSpinAddr = update.getSpinPostalAddr();
        				strStreet = update.getStreet();
        				strPOBox = update.getPOBox();
        				strCity = update.getCity();
        				strState = update.getState();
        				strZipCode = update.getZipCode();
        				strCountry = update.getCountry();
        				strSpinSNS = update.getSpinSNS();
        				strSNS = update.getSNS();
        				strSpinOrg1 = update.getSpinOrg1();
        				strOrg1 = update.getOrg1();
        				strSpinOrg2 = update.getSpinOrg2();
        				strOrg2 = update.getOrg2();		
        				strNotes = update.getNotes();
        				strTime = update.getTime();
        				
        				photoSize = update.getPhotosize();        				       				            			    				
        				packet_photo = update.getPhoto(Integer.parseInt(photoSize));        				
        				      				        				        			        							
        				packetTime = Long.parseLong(update.getTime());
        				            				
        				send_packet = new DatagramPacket(buf,buf.length);
        				iadd = InetAddress.getByName(CLIENTIP);        				        				
        				
        				if(strVersion.equalsIgnoreCase("UDPAndcontact1"))
        					CLIENTPORT_ACK = 7000;
        				else if(strVersion.equalsIgnoreCase("UDPAndcontact2"))
        					CLIENTPORT_ACK = 6000;
        				else if(strVersion.equalsIgnoreCase("UDPAndcontact3"))
        					CLIENTPORT_ACK = 5800;
        				else 
        					CLIENTPORT_ACK = 8000;
        				
        				JSONObject jsonUpdate_ack = new JSONObject();  
        				String stringUpdate_ack = jsonUpdate_ack.toString();  
        				send_packet=new DatagramPacket( stringUpdate_ack.getBytes(), stringUpdate_ack.getBytes().length, iadd, CLIENTPORT_ACK);
        				        				
        				// packet ack
        				socket.send(send_packet);
        				
        				try {
        		        	
        		        	mDbHelper_server.open();        		    		
        		        	cur = mDbHelper_server.fetchAllContacts(); 
        		        	
        		        	numRow = cur.getCount();            		        	
        		        	        		        	
        		        	if(cur != null){
        		        		if (cur.moveToFirst()){
        		        			
        		        			count = 0;
        		        			do{
        		        				
        		        				count++;
        		        				
        		        				Version = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_VERSION));
        		        				Types = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_TYPES));
        		        				Owner = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_OWNER));
        		        				photo = cur.getBlob(cur.getColumnIndex(ContactDBAdapter.KEY_PHOTO));
        		            			GivenName = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_GIVENNAME));
        		            			MiddleName = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_MIDDLENAME));
        		            			FamilyName = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_FAMILYNAME));
        		            			Gender = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_GENDER));
        		            			SpinPhone = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_SPINPHONE));
        		            			Phone = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_PHONE));
        		            			SpinEmail = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_SPINEMAIL));
        		            			Email = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_EMAIL));
        		            			SpinIM = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_SPINIM));
        		            			IM = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_IM));
        		            			SpinPostalAddr = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_SPINADDR));
        		            			Street = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_STREET));
        		            			POBox = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_POBOX));
        		            			City = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_CITY));
        		            			State = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_STATE));
        		            			ZipCode = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_ZIPCODE));
        		            			Country = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_COUNTRY));
        		            			SpinSNS = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_SPINSNS));
        		            			SNS = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_SNS));
        		            			SpinOrg1 = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_SPINORG1));
        		            			Org1 = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_ORG1));
        		            			SpinOrg2 = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_SPINORG2));
        		            			Org2 = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_ORG2));            		            			
        		            			Notes = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_NOTES));
        		            			Time = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_TIME));
        		            			        		            			
        		        				dbTime = Long.parseLong(Time);
        		        				
        		        				Long packet_time = new Long(packetTime);
        		        				Long db_time = new Long(dbTime);
        		        					
        		        				int comp = packet_time.compareTo(db_time);

        	            				if((strGivenName.compareTo(GivenName) ==  0) && (strFamilyName.compareTo(FamilyName) == 0)){ //if givenname and familyname are same
        	            						
        	            					if((strSpinOrg1.compareTo(SpinOrg1) == 0) || (strSpinOrg2.compareTo(SpinOrg2) == 0)) {
        	            					            	           
        	            						if(comp < 0){            	            						            	            						
        	            							 
        	            							update.setTypes(Version);
        	            							update.setTypes(Types); 
        	            							update.setOwner(Owner);
        	            							update.setGivenName(GivenName);   
        	            							update.setMiddleName(MiddleName);   
        	            							update.setFamilyName(FamilyName);           
        	            							update.setGender(Gender);                    
        	            							update.setSpinPhone(SpinPhone);                    
        	            							update.setPhone(Phone);                    
        	            							update.setSpinEmail(SpinEmail);                    
        	            							update.setEmail(Email);                     
        	            							update.setSpinIM(SpinIM);                    
        	            							update.setIM(IM);                     
        	            							update.setSpinPostalAddr(SpinPostalAddr);                    
        	            							update.setStreet(Street);                    
        	            							update.setPOBox(POBox);                    
        	            							update.setCity(City);                   
        	            							update.setState(State);                    
        	            							update.setZipCode(ZipCode);                    
        	            							update.setCountry(Country);                    
        	            							update.setSpinSNS(SpinSNS);                    
        	            							update.setSNS(SNS);                    
        	            							update.setSpinOrg1(SpinOrg1);                   
        	            							update.setOrg1(Org1);
        	            							update.setSpinOrg2(SpinOrg2);                   
        	            							update.setOrg2(Org2);
        	            							update.setNotes(Notes);
        	            							update.setTime(Time);
        	            							update.setPhoto(photo);
        	            							
        	            							send_packet=new DatagramPacket( update.update_packet, update.update_packet.length, iadd, CLIENTPORT);
        	            							socket.send(send_packet);                     
        	            							       	            							
        	            							break;
        	            							
        	            						} else if(comp == 0){        	            							
        	            							break;
        	            							
        	            						} else {
        	            						
        	            							String rowId = cur.getString(cur.getColumnIndexOrThrow(ContactDBAdapter.KEY_ROWID));                                                

        	            							update_contact = mDbHelper_server.updateContact(Long.parseLong(rowId), strVersion, strTypes, strOwner,strGivenName, strMiddleName, strFamilyName, strGender, strSpinPhone, 
		        						 		 			 		strPhone, strSpinEmail, strEmail, strSpinIM, strIM, strSpinAddr, strStreet, strPOBox, strCity, strState, strZipCode,
		        						 		 			 		strCountry, strSpinSNS, strSNS, strSpinOrg1, strOrg1, strSpinOrg2, strOrg2, strNotes, strTime, packet_photo);               		                    		        						     						
        	            							
        	            							send_packet=new DatagramPacket( update.update_packet, update.update_packet.length, iadd, CLIENTPORT);            	            							
        	            							socket.send(send_packet);
        	            							      	            							        	            						
        	            							break;
        	            						} 
        	            					}         	            					        	            					
        	            				  } else{ //different givenname and familyname
            	            					
          	            					  if(numRow == count){
            	            						          	            						  	
            	            						contact_id = mDbHelper_server.createContact(strVersion, strTypes, strOwner, strGivenName, strMiddleName, strFamilyName, strGender, strSpinPhone, strPhone, 
            	            									 strSpinEmail, strEmail, strSpinIM, strIM, strSpinAddr, strStreet, strPOBox, strCity, strState, 
            	            									 strZipCode, strCountry, strSpinSNS, strSNS, strSpinOrg1, strOrg1, strSpinOrg2, strOrg2, strNotes, strTime, packet_photo);
            	            						
            	            						send_packet=new DatagramPacket( update.update_packet, update.update_packet.length, iadd, CLIENTPORT);                	            						                	            						
            	            						socket.send(send_packet);
            	            						        	            							
          	            					  }            	            				
        	            				  }                    	            				         	  
        		        			}while (cur.moveToNext());        		        			
        		        		} //if
        		        	} // if
        		        	cur.close();         		       	        	
        		        } catch (Exception e) {
        					e.printStackTrace();
        		        }
        			} catch(IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch(NullPointerException e) {
                    	e.printStackTrace();	
                    } catch(NumberFormatException e){
       		       	 	e.printStackTrace();
    		        }                     
        		} //while          				
        } catch (UnknownHostException e) {
        	// TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();       
        }         
    } //run    
} //Server